package com.heima.sync.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.search.SearchConstants;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.sync.mapper.ApArticleMapper;
import com.heima.sync.service.EsDataService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class EsDataServiceImpl implements EsDataService {

    @Autowired
    private RestHighLevelClient client;//es的java客户端
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 将数据初始化到es索引库中
     */
    @Override
    public ResponseResult dataInit() {
        //判断索引库是否存在
        if (client == null) {
            //todo 索引库不存在则根据映射关系创建索引库
        }
        //获取所有待上传到es索引库的文章
        List<ApArticle> allArticles = apArticleMapper.findAllArticles();
        if (CollectionUtils.isEmpty(allArticles))
            return ResponseResult.okResult(AppHttpCodeEnum.DATA_EXIST.getCode(), "当前暂无待上传索引库的文章");
        //获取添加对象的api
        BulkRequest bulkRequest = new BulkRequest(SearchConstants.ARTICLE_INDEX_NAME);//括号里面的内容是索引库的名字
        try {
            //批量添加文档
            for (ApArticle allArticle : allArticles) {
                IndexRequest request = new IndexRequest();//获取添加文档的请求对象
                //将每一个待上传索引库的对象转换成json
                SearchArticleVo searchArticleVo = new SearchArticleVo();
                BeanUtils.copyProperties(allArticle, searchArticleVo);
                String s = JSON.toJSONString(searchArticleVo);
                request.id(String.valueOf(searchArticleVo.getId()));
                //添加文档
                request.source(s, XContentType.JSON);
                //添加到桶中
                bulkRequest.add(request);
            }
            //向es发送请求
            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            return ResponseResult.okResult(response.status());
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "批量插入索引库失败");
        }
    }
}
